<template>
	<view class="page search-page">
		<!-- 搜索头部 -->
		<view class="search-header">
			<view class="search-container">
				<text class="back-btn" @click="goBack">←</text>
				<view class="search-input-wrapper">
					<input 
						v-model="searchKeyword"
						type="text" 
						placeholder="搜索联系人、聊天记录"
						class="search-input"
						focus
						@input="onSearchInput"
						@confirm="handleSearch"
					/>
					<text v-if="searchKeyword" class="clear-btn" @click="clearSearch">×</text>
				</view>
			</view>
		</view>
		
		<view class="content">
			<!-- 搜索过滤器 -->
			<view class="filter-section">
				<view class="filter-tabs">
					<view 
						v-for="(tab, index) in filterTabs" 
						:key="index"
						class="filter-tab" 
						:class="{ active: currentTab === tab.value }"
						@click="switchTab(tab.value)"
					>
						<text class="tab-text">{{ tab.label }}</text>
					</view>
				</view>
			</view>
			
			<!-- 搜索结果 -->
			<view v-if="searchKeyword && hasSearched" class="results-section">
				<!-- 联系人结果 -->
				<view v-if="(currentTab === 'all' || currentTab === 'contacts') && contactResults.length > 0" class="result-group">
					<view class="group-header">
						<text class="group-title">联系人</text>
						<text class="group-count">{{ contactResults.length }}</text>
					</view>
					<view class="result-list">
						<view 
							v-for="contact in displayedContacts" 
							:key="contact.id"
							class="result-item"
							@click="openChat(contact)"
						>

							<image :src="contact.avatar" class="result-avatar" mode="aspectFill" />
							<view class="result-info">
								<text class="result-name" v-html="highlightKeyword(contact.nickname)"></text>
							</view>
							<view v-if="contact.unreadCount > 0" class="unread-badge">
								{{ contact.unreadCount }}
							</view>
						</view>
					</view>
					<view v-if="contactResults.length > 3 && !showAllContacts" class="show-more" @click="showAllContacts = true">
						<text class="show-more-text">查看更多联系人 ({{ contactResults.length - 3 }})</text>
					</view>
				</view>
				
				<!-- 群聊结果 -->
				<view v-if="(currentTab === 'all' || currentTab === 'groups') && groupResults.length > 0" class="result-group">
					<view class="group-header">
						<text class="group-title">群聊</text>
						<text class="group-count">{{ groupResults.length }}</text>
					</view>
					<view class="result-list">
						<view 
							v-for="group in displayedGroups" 
							:key="group.id"
							class="result-item"
							@click="openChat(group)"
						>
							<image :src="group.avatar" class="result-avatar" mode="aspectFill" />
							<view class="result-info">
								<text class="result-name" v-html="highlightKeyword(group.name)"></text>
								<text class="result-desc">{{ group.memberCount }}人 · {{ group.lastMessage || '暂无消息' }}</text>
							</view>
							<view v-if="group.unreadCount > 0" class="unread-badge">
								{{ group.unreadCount }}
							</view>
						</view>
					</view>
					<view v-if="groupResults.length > 3 && !showAllGroups" class="show-more" @click="showAllGroups = true">
						<text class="show-more-text">查看更多群聊 ({{ groupResults.length - 3 }})</text>
					</view>
				</view>
				
				<!-- 聊天记录结果 -->
				<view v-if="(currentTab === 'all' || currentTab === 'messages') && messageResults.length > 0" class="result-group">
					<view class="group-header">
						<text class="group-title">聊天记录</text>
						<text class="group-count">{{ messageResults.length }}</text>
					</view>
					<view class="result-list">
						<view 
							v-for="message in displayedMessages" 
							:key="message.id"
							class="result-item message-item"
							@click="jumpToMessage(message)"
						>
							<image :src="message.senderAvatar" class="result-avatar" mode="aspectFill" />
							<view class="result-info">
								<view class="message-header">
									<text class="result-name">{{ message.senderName }}</text>
									<text class="message-time">{{ formatTime(message.timestamp) }}</text>
								</view>
								<text class="result-desc" v-html="highlightKeyword(message.content)"></text>
								<text class="message-from">来自：{{ message.conversationName }}</text>
							</view>
						</view>
					</view>
					<view v-if="messageResults.length > 5 && !showAllMessages" class="show-more" @click="showAllMessages = true">
						<text class="show-more-text">查看更多聊天记录 ({{ messageResults.length - 5 }})</text>
					</view>
				</view>
				
				<!-- 空结果 -->
				<view v-if="isEmptyResult" class="empty-state">
					<ob-empty 
						:image="'/static/images/empty-search.png'"
						title="未找到相关内容"
						description="尝试使用其他关键词搜索"
					/>
				</view>
			</view>
			
			<!-- 搜索历史 -->
			<view v-if="!searchKeyword && searchHistory.length > 0" class="history-section">
				<view class="section-header">
					<text class="section-title">搜索历史</text>
					<text class="clear-history" @click="clearHistory">清空</text>
				</view>
				<view class="history-list">
					<view 
						v-for="(item, index) in searchHistory" 
						:key="index"
						class="history-item"
						@click="searchFromHistory(item)"
					>
						<text class="history-keyword">{{ item }}</text>
						<text class="delete-history" @click.stop="deleteHistoryItem(index)">×</text>
					</view>
				</view>
			</view>
			
			<!-- 热门搜索 -->
			<view v-if="!searchKeyword && hotSearches.length > 0" class="hot-section">
				<view class="section-header">
					<text class="section-title">热门搜索</text>
				</view>
				<view class="hot-list">
					<view 
						v-for="(item, index) in hotSearches" 
						:key="index"
						class="hot-item"
						@click="searchFromHistory(item)"
					>
						<text class="hot-keyword">{{ item }}</text>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 加载组件 -->
		<ob-loading :visible="isSearching" text="搜索中..." />
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import messageApi from '../../api/message.js'
import aiApi from '../../api/ai.js'
import { formatDistanceToNow } from '../../utils/common.js'

// 响应式数据
const searchKeyword = ref('')
const currentTab = ref('all')
const contactResults = ref([])
const groupResults = ref([])
const messageResults = ref([])
const searchHistory = ref([])
const hotSearches = ref(['订单', '发货', '商品', '客服', '物流'])
const isSearching = ref(false)
const hasSearched = ref(false)
const showAllContacts = ref(false)
const showAllGroups = ref(false)
const showAllMessages = ref(false)

// 搜索过滤器选项
const filterTabs = [
	{ label: '全部', value: 'all' },
	{ label: '联系人', value: 'contacts' },
	// { label: '群聊', value: 'groups' },
	{ label: '聊天记录', value: 'messages' }
]

// 计算属性
const displayedContacts = computed(() => {
	return showAllContacts.value ? contactResults.value : contactResults.value.slice(0, 3)
})

const displayedGroups = computed(() => {
	return showAllGroups.value ? groupResults.value : groupResults.value.slice(0, 3)
})

const displayedMessages = computed(() => {
	return showAllMessages.value ? messageResults.value : messageResults.value.slice(0, 5)
})

const isEmptyResult = computed(() => {
	return hasSearched.value && 
	       contactResults.value.length === 0 && 
	       groupResults.value.length === 0 && 
	       messageResults.value.length === 0
})

// 生命周期
onMounted(() => {
	loadSearchHistory()
})

// 方法
const goBack = () => {
	uni.navigateBack()
}

const onSearchInput = () => {
	// 重置展开状态
	showAllContacts.value = false
	showAllGroups.value = false
	showAllMessages.value = false
	
	// 防抖搜索
	clearTimeout(window.searchTimer)
	window.searchTimer = setTimeout(() => {
		if (searchKeyword.value.trim()) {
			handleSearch()
		} else {
			resetSearchResults()
		}
	}, 300)
}

const handleSearch = async () => {
	if (!searchKeyword.value.trim() || isSearching.value) return
	
	try {
		isSearching.value = true
		hasSearched.value = true
		
		const keyword = searchKeyword.value.trim()
		
		// 添加到搜索历史
		addToSearchHistory(keyword)
		
		// 获取用户信息
		const userInfo = uni.getStorageSync('userInfo') || {}
		const userId = userInfo?.id || userInfo?.userId

		// 同时搜索普通消息和AI会话
		const [messageResponse, aiResponse] = await Promise.all([
			messageApi.searchAll({
				keyword,
				type: currentTab.value
			}).catch(err => {
				console.log('普通消息搜索请求失败:', err.message || err)
				return { data: { contacts: [], groups: [], messages: [] } }
			}),
			userId ? aiApi.searchConversations({
				userId,
				keyword,
				page: 1,
				size: 20
			}).catch(err => {
				console.log('AI会话搜索请求失败:', err.message || err)
				return { data: { conversations: [] } }
			}) : Promise.resolve({ data: { conversations: [] } })
		])

		console.log('普通消息搜索响应:', messageResponse)
		console.log('AI会话搜索响应:', aiResponse)

		// 处理普通消息搜索结果 - 修复数据结构访问
		const messageData = messageResponse.data || messageResponse
		contactResults.value = messageData.contacts || []
		groupResults.value = messageData.groups || []
		let normalMessages = messageData.messages || []

		// 处理AI会话搜索结果
		let aiMessages = []
		const aiData = aiResponse.data || aiResponse
		if (aiData && aiData.conversations) {
			aiMessages = aiData.conversations.map(conversation => ({
				id: conversation.conversationId,
				content: conversation.lastMessage || '暂无消息',
				senderName: 'AI助手',
				senderAvatar: '/static/images/ai-avatar.png',
				timestamp: conversation.updateTime || conversation.lastMessageTime,
				conversationName: conversation.title || 'AI对话',
				conversationId: conversation.conversationId,
				isAiConversation: true
			}))
		}

		// 合并消息结果
		messageResults.value = [...normalMessages, ...aiMessages]

		// 按时间排序
		messageResults.value.sort((a, b) => {
			const timeA = new Date(a.timestamp).getTime()
			const timeB = new Date(b.timestamp).getTime()
			return timeB - timeA
		})
		
	} catch (error) {
		console.error('搜索失败:', error)
		// 静默处理错误，不显示用户提示
		// 重置搜索结果为空
		contactResults.value = []
		groupResults.value = []
		messageResults.value = []
	} finally {
		isSearching.value = false
	}
}

const switchTab = (tabValue) => {
	currentTab.value = tabValue
	if (searchKeyword.value.trim()) {
		handleSearch()
	}
}

const clearSearch = () => {
	searchKeyword.value = ''
	resetSearchResults()
}

const resetSearchResults = () => {
	contactResults.value = []
	groupResults.value = []
	messageResults.value = []
	hasSearched.value = false
	showAllContacts.value = false
	showAllGroups.value = false
	showAllMessages.value = false
}

const highlightKeyword = (text) => {
	if (!searchKeyword.value || !text) return text
	
	const keyword = searchKeyword.value.trim()
	const regex = new RegExp(`(${keyword})`, 'gi')
	return text.replace(regex, '<span style="color: #495057; font-weight: 600;">$1</span>')
}

const openChat = (item) => {
	// 构建跳转URL，包含必要的用户信息
	let url = `/pages/message/chat?conversationId=${item.conversationId}&type=${item.type || 'private'}`

	// 添加用户信息
	if (item.name) {
		url += `&name=${encodeURIComponent(item.name)}`
	}
	if (item.nickname) {
		url += `&nickname=${encodeURIComponent(item.nickname)}`
	}
	if (item.avatar) {
		url += `&avatar=${encodeURIComponent(item.avatar)}`
	}
	if (item.id) {
		url += `&toUserId=${item.id}`
	}

	uni.navigateTo({ url })
}

const jumpToMessage = (message) => {
	console.log('跳转到消息:', message)

	// 检查是否是AI会话
	if (message.isAiConversation || (message.conversationId && message.conversationId.startsWith('ai_'))) {
		// AI会话跳转
		const url = `/pages/message/ai-chat?conversationId=${message.conversationId}`
		uni.navigateTo({ url })
		return
	}

	// 构建跳转URL，包含消息定位信息
	let url = `/pages/message/chat?conversationId=${message.conversationId}&messageId=${message.id}`

	// 添加对方用户ID（重要：用于聊天页面确定对话对象）
	if (message.toUserId) {
		url += `&toUserId=${message.toUserId}`
	}

	// 使用对话对象的信息进行跳转（优先使用昵称）
	const displayName = message.conversationPartnerNickname || message.conversationPartnerName || message.senderName;
	const userName = message.conversationPartnerName || message.senderName;

	if (displayName) {
		url += `&name=${encodeURIComponent(userName)}`
		url += `&nickname=${encodeURIComponent(displayName)}`
	}
	if (message.conversationPartnerAvatar) {
		url += `&avatar=${encodeURIComponent(message.conversationPartnerAvatar)}`
	}

	// 添加消息的发送方和接收方ID（用于调试和扩展功能）
	if (message.fromId) {
		url += `&fromId=${message.fromId}`
	}
	if (message.toId) {
		url += `&toId=${message.toId}`
	}

	console.log('跳转到聊天记录:', {
		conversationId: message.conversationId,
		messageId: message.id,
		toUserId: message.toUserId,
		conversationPartnerName: message.conversationPartnerName,
		senderName: message.senderName,
		fromId: message.fromId,
		toId: message.toId,
		url: url
	})

	uni.navigateTo({ url })
}

const formatTime = (timestamp) => {
	if (!timestamp) return ''
	return formatDistanceToNow(timestamp)
}

// 搜索历史管理
const loadSearchHistory = () => {
	const history = uni.getStorageSync('searchHistory') || []
	searchHistory.value = history.slice(0, 10) // 最多显示10个
}

const addToSearchHistory = (keyword) => {
	const history = searchHistory.value.filter(item => item !== keyword)
	history.unshift(keyword)
	searchHistory.value = history.slice(0, 10)
	
	uni.setStorageSync('searchHistory', searchHistory.value)
}

const searchFromHistory = (keyword) => {
	searchKeyword.value = keyword
	handleSearch()
}

const deleteHistoryItem = (index) => {
	searchHistory.value.splice(index, 1)
	uni.setStorageSync('searchHistory', searchHistory.value)
}

const clearHistory = () => {
	uni.showModal({
		title: '清空搜索历史',
		content: '确定要清空所有搜索历史吗？',
		success: (res) => {
			if (res.confirm) {
				searchHistory.value = []
				uni.removeStorageSync('searchHistory')
			}
		}
	})
}
</script>

<style lang="scss" scoped>
.search-page {
	background: #FAFAFA;
	min-height: 100vh;
}

.search-header {
	background: #FFFFFF;
	padding: 10px 15px;
	border-bottom: 1px solid #F0F0F0;
}

.search-container {
	display: flex;
	align-items: center;
	gap: 10px;
}

.back-btn {
	font-size: 18px;
	color: #333333;
	padding: 5px;
}

.search-input-wrapper {
	flex: 1;
	position: relative;
	display: flex;
	align-items: center;
}

.search-input {
	flex: 1;
	background: #F8F9FA;
	border: 1px solid #E9ECEF;
	border-radius: 20px;
	padding: 8px 15px;
	font-size: 14px;
	height: 40px;
	box-sizing: border-box;
}

.clear-btn {
	position: absolute;
	right: 15px;
	font-size: 16px;
	color: #999999;
	width: 20px;
	text-align: center;
}

.content {
	flex: 1;
}

.filter-section {
	background: #FFFFFF;
	border-bottom: 1px solid #F0F0F0;
}

.filter-tabs {
	display: flex;
	padding: 0 15px;
}

.filter-tab {
	flex: 1;
	text-align: center;
	padding: 15px 0;
	position: relative;
	
	&.active {
		.tab-text {
			color: #495057;
			font-weight: 600;
		}
		
		&::after {
			content: '';
			position: absolute;
			bottom: 0;
			left: 50%;
			transform: translateX(-50%);
			width: 30px;
			height: 2px;
			background: #495057;
		}
	}
}

.tab-text {
	font-size: 14px;
	color: #999999;
}

.results-section {
	padding: 10px 0;
}

.result-group {
	background: #FFFFFF;
	margin-bottom: 10px;
}

.group-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px 10px;
}

.group-title {
	font-size: 14px;
	font-weight: 600;
	color: #333333;
}

.group-count {
	font-size: 12px;
	color: #999999;
}

.result-list {
	padding: 0 20px;
}

.result-item {
	display: flex;
	align-items: center;
	padding: 12px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
	
	&:active {
		background: #F8F9FA;
	}
}

.result-avatar {
	width: 45px;
	height: 45px;
	border-radius: 22.5px;
	margin-right: 12px;
}

.result-info {
	flex: 1;
	min-width: 0;
}

.result-name {
	font-size: 16px;
	font-weight: 500;
	color: #333333;
	display: block;
	margin-bottom: 4px;
}

.result-desc {
	font-size: 12px;
	color: #999999;
	overflow: hidden;
	text-overflow: ellipsis;
	white-space: nowrap;
}

.message-item {
	.message-header {
		display: flex;
		align-items: center;
		justify-content: space-between;
		margin-bottom: 4px;
	}
	
	.message-time {
		font-size: 12px;
		color: #999999;
		flex-shrink: 0;
	}
	
	.message-from {
		font-size: 11px;
		color: #999999;
		margin-top: 2px;
	}
}

.unread-badge {
	background: #DC3545;
	color: #FFFFFF;
	font-size: 12px;
	padding: 2px 6px;
	border-radius: 10px;
	min-width: 18px;
	text-align: center;
	flex-shrink: 0;
}

.show-more {
	padding: 10px 20px;
	text-align: center;
	border-top: 1px solid #F8F9FA;
	
	&:active {
		background: #F8F9FA;
	}
}

.show-more-text {
	font-size: 14px;
	color: #495057;
}

.empty-state {
	padding: 50px 20px;
}

.history-section,
.hot-section {
	background: #FFFFFF;
	margin: 10px 0;
}

.section-header {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 15px 20px;
	border-bottom: 1px solid #F0F0F0;
}

.section-title {
	font-size: 16px;
	font-weight: 600;
	color: #333333;
}

.clear-history {
	font-size: 14px;
	color: #999999;
}

.history-list {
	padding: 10px 20px;
}

.history-item {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 12px 0;
	border-bottom: 1px solid #F8F9FA;
	
	&:last-child {
		border-bottom: none;
	}
}

.history-keyword {
	font-size: 14px;
	color: #333333;
	flex: 1;
}

.delete-history {
	font-size: 16px;
	color: #999999;
	width: 20px;
	text-align: center;
}

.hot-list {
	padding: 15px 20px;
	display: flex;
	flex-wrap: wrap;
	gap: 10px;
}

.hot-item {
	background: #F8F9FA;
	border-radius: 15px;
	padding: 8px 15px;
	
	&:active {
		background: #E9ECEF;
	}
}

.hot-keyword {
	font-size: 12px;
	color: #6C757D;
}
</style>